package org.dyndns.blackpaw.whirlmon;

import java.util.Date;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v4.app.ListFragment;
import android.support.v4.view.MenuItemCompat;
import android.text.format.DateUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;

public class RecentFragment extends ListFragment {

	static final String LOGTAG = "RECENT";

	class WPThreadArrayAdapter extends ArrayAdapter<WPThread> {
		public WPThreadArrayAdapter(Context context, WPThread.List threads) {
			super(context, R.layout.recent_row_view, threads);
		}

		
        @Override
        public android.view.View getView(int position, View convertView,
                ViewGroup parent) {

            LayoutInflater inflater = (LayoutInflater) getContext()
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

            View listItemView = convertView;
            if (null == convertView) {
                listItemView = inflater
                        .inflate(R.layout.recent_row_view, parent, false);
            }

            WPThread t = (WPThread) getItem(position);
            
            // Separator View
            boolean sectionStart = (position == 0);
            if (!sectionStart) {
                // Check previous item
                WPThread prev = (WPThread) getItem(position - 1);
                sectionStart = (t.forumId != prev.forumId);
            }
            if (sectionStart) {
                TextView viewSep = (TextView) listItemView
                        .findViewById(R.id.recent_separator);
                viewSep.setVisibility(View.VISIBLE);
                viewSep.setText(t.forumName);
            }

            
            
            // title
            TextView viewTitle = (TextView) listItemView
                    .findViewById(R.id.recent_title);
            viewTitle.setText(t.title);

            // Replies
            TextView viewReplies = (TextView) listItemView.findViewById(R.id.recent_replies);
            viewReplies.setText(Integer.toString(t.replies));
            

            // Last Replier
            TextView viewLastName = (TextView) listItemView.findViewById(R.id.recent_lastName);
            viewLastName.setText(t.lastName);
            
            
            // Source
            TextView viewSource = (TextView) listItemView
                    .findViewById(R.id.recent_source);

            String s = "";

            // Check for differences between server and local time
            // Service can be ahead by a few minutes which leads to odd looking
            // time strings :)
            Date d = t.lastDate;
            Date now = new Date();
            if (d.after(now))
                d = now;
            s += DateUtils.getRelativeDateTimeString(getActivity()
                    .getApplicationContext(), d.getTime(),
                    DateUtils.MINUTE_IN_MILLIS, DateUtils.WEEK_IN_MILLIS,
                    DateUtils.FORMAT_12HOUR);
            
            viewSource.setText(s);

            return listItemView;
        }	
	}

	WPThreadArrayAdapter adaptor;

	/**
	 * The Fragment's UI is just a simple text view showing its instance number.
	 */
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		Log.i(LOGTAG, "onCreateView");
		setHasOptionsMenu(true);
		View v = inflater.inflate(R.layout.recent, container, false);
		return v;
	}

	@Override
	public void onListItemClick(ListView l, View v, int position, long id) {
		super.onListItemClick(l, v, position, id);
		DoOnItemClick(l, v, position, id);
	}

	protected void DoOnItemClick(AdapterView<?> av, View view, int i, long l) {
		final WPThread th = adaptor.getItem(i);
		// http://forums.whirlpool.net.au/forum-replies.cfm?t=1220737
		Uri uriUrl = Uri
				.parse("http://forums.whirlpool.net.au/forum-replies.cfm?t="
						+ th.id + "&p=-1#bottom");
		Intent launchBrowser = new Intent(Intent.ACTION_VIEW, uriUrl);
		startActivity(launchBrowser);
	}

	@Override
	public void onStart() {
		// TODO Auto-generated method stub
		super.onStart();
		RefreshRecentThreads();
	}

	@Override
	public void onStop() {
		if (currentTask != null)
			currentTask.cancel(true);
		super.onStop();
	}

	private class RecentThreadsTask extends AsyncTask<String, Void, Void> {

		WPThread.List w = null;

		@Override
		protected void onPreExecute() {
			getActivity().setProgressBarIndeterminateVisibility(true);
		}

		@Override
		protected Void doInBackground(String... params) {
			try {

				String apiKey = params[0];
				boolean ignoreOwn = Boolean.parseBoolean(params[1]);
				w = WPThread.getRecent(apiKey, ignoreOwn);
			} catch (Throwable x) {
				Log.e(LOGTAG, "RecentThreadsTask", x);
			}
			return null;
		}

		@Override
		protected void onPostExecute(Void result) {
			currentTask = null;
			if (getActivity() == null) {
				Log.i(LOGTAG, "onPostExecute - Activity stopped");
			} else {
				getActivity().setProgressBarIndeterminateVisibility(false);
				UpdateRecentThreadsUI(w);
			}
		}

		@Override
		protected void onCancelled() {
			Log.i(LOGTAG, "Cancelled");
			currentTask = null;
			super.onCancelled();
		}

	}

	RecentThreadsTask currentTask = null;

	private void RefreshRecentThreads() {
		if (currentTask != null)
			currentTask.cancel(true);
		SharedPreferences sharedPrefs = PreferenceManager
				.getDefaultSharedPreferences(getActivity());
		String apiKey = sharedPrefs.getString("api_key", "");
		boolean ignoreOwn = sharedPrefs.getBoolean("ignore_own_posts", true);
		currentTask = new RecentThreadsTask();
		currentTask.execute(apiKey, Boolean.toString(ignoreOwn));
	}

	private void UpdateRecentThreadsUI(WPThread.List w) {
		Log.i(LOGTAG, "UpdateRecentThreads");
		try {
			if (w == null)
				throw new Exception("No data");

			adaptor = new WPThreadArrayAdapter(getActivity(), w);
			setListAdapter(adaptor);
		} catch (Throwable x) {
			Log.e(LOGTAG, "UpdateRecentThreads", x);
		}

	}

	@Override
	public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
		super.onCreateOptionsMenu(menu, inflater);
		inflater.inflate(R.menu.recent_menu, menu);
		MenuItemCompat.setShowAsAction(menu.findItem(R.id.refresh),
				MenuItemCompat.SHOW_AS_ACTION_IF_ROOM);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.refresh:
			RefreshRecentThreads();
			return true;

		default:
			return super.onOptionsItemSelected(item);
		}
	}
}
